package com.letwal.cmcvnd.transfer

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.letwal.cmcvnd.R
import com.letwal.cmcvnd.adata.withdraw.ReqWithdrawCreate
import com.letwal.cmcvnd.aviewmodel.WithdrawViewModel
import com.letwal.cmcvnd.base.BaseActivity
import com.letwal.cmcvnd.components.dialog.EnterTransferPasswordDialog
import com.letwal.cmcvnd.databinding.ActivityTransferBinding
import com.letwal.cmcvnd.enums.PageTagEnum
import com.letwal.cmcvnd.extend.*
import java.text.SimpleDateFormat
import java.util.Date

/** 交换页 */
@SuppressLint("CustomSplashScreen")
class TransferActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityTransferBinding

    //密码弹框
    private lateinit var mEnterTransferPasswordDialog: EnterTransferPasswordDialog

    //单位
    private var mCoinUnit = ""

    //余额
    private var mBalance = ""

    //withdraw viewModel
    private val mWithdrawViewModel by lazy {
        ViewModelProvider(this)[WithdrawViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mWithdrawViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.my_wallet.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding =
            ActivityTransferBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onContentViewBinded() {
        try {
            //监听返回
            onHandleLiveDataCallback()

            //输入监听
            onHandleEditInputChanged()

            //初始化
            mEnterTransferPasswordDialog = EnterTransferPasswordDialog()
            mEnterTransferPasswordDialog.setConfirmClickListener { password ->
                //发起转账
                val coinType = intent.getStringExtra("coinType").toString()
                val address = mActivityBinding.editTransferAddress.text.toString().trim()
                val amount = mActivityBinding.editTransferCount.text.toString().trim()
                mWithdrawViewModel.withdrawCreate(
                    ReqWithdrawCreate(
                        coinType = coinType,
                        address = address,
                        amount = amount
                    )
                )
            }

            //点击确认
            mActivityBinding.submitTransfer.setOnClickListener {
                val amount = mActivityBinding.editTransferCount.text.toString().trim()
                val address = mActivityBinding.editTransferAddress.text.toString().trim()
                val balance = mBalance.toAmountDouble()

                if (balance > 0) {
                    if (address.isNotBlank()) {
                        if (amount.toAmountDouble() > 0) {
                            mEnterTransferPasswordDialog.showDialog(
                                supportFragmentManager,
                                getString(R.string.withdraw_enter_your_password)
                            )
                        } else {
                            Toast.makeText(
                                this,
                                getString(R.string.transfer_err_tips1),
                                Toast.LENGTH_SHORT
                            )
                                .show()
                        }
                    } else {
                        Toast.makeText(
                            this,
                            getString(R.string.transfer_err_tips2),
                            Toast.LENGTH_SHORT
                        )
                            .show()
                    }
                } else {
                    Toast.makeText(this, getString(R.string.transfer_err_tips3), Toast.LENGTH_SHORT)
                        .show()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        //初始化配置参数
        val coinType = intent.getStringExtra("coinType").toString()
        println("=====coinType:$coinType")

        //获取余额
        mWithdrawViewModel.withdrawGetBalance(ReqWithdrawCreate(coinType = coinType))
    }

    /** 监听live data 返回 */
    @SuppressLint("NotifyDataSetChanged", "SetTextI18n", "SimpleDateFormat")
    private fun onHandleLiveDataCallback() {
        mWithdrawViewModel.onWithdrawGetBalanceLiveData.observe(this) {
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    mCoinUnit = result.unit
                    mBalance = result.balance
                    mActivityBinding.textTransferAmount.text =
                        result.balance.toFinanceString() + " " + mCoinUnit

                    mActivityBinding.textTransferBalanceAmount.text =
                        result.balance.toFinanceString() + " " + mCoinUnit
                }
            }
        }

        mWithdrawViewModel.onWithdrawCreateLiveData.observe(this) {
            if (it.isSuccess) {
                mEnterTransferPasswordDialog.dismiss()

                val dateFormat = SimpleDateFormat("dd/MM/yyyy")
                val date = dateFormat.format(Date())

                val coinType = intent.getStringExtra("coinType").toString()
                val address = mActivityBinding.editTransferAddress.text.toString().trim()
                val amount = mActivityBinding.editTransferCount.text.toString().trim()
                val params = HashMap<String, String>()
                params["amount"] = amount
                params["address"] = address
                params["date"] = date
                params["unit"] = mCoinUnit
                params["coinType"] = coinType

                startToTransferResultActivity(hashMap = params)

                //清空
                mActivityBinding.editTransferCount.setText(null)
            }
        }
    }

    /** 输入监听 */
    private fun onHandleEditInputChanged() {
        mActivityBinding.editTransferAddress.addTextChangedListener(object :
            TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                //判断提交按键是否可用
                val address = mActivityBinding.editTransferAddress.text.toString().trim()
                val amount = mActivityBinding.editTransferCount.text.toString().trim()
                if (address.isNotBlank() and amount.isNotBlank()) {
                    mActivityBinding.submitTransfer.setBackgroundResource(R.drawable.main_btn_hightlight)
                } else {
                    mActivityBinding.submitTransfer.setBackgroundResource(R.drawable.main_btn_ban)
                }
            }
        })

        mActivityBinding.editTransferCount.addTextChangedListener(object :
            TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                //判断提交按键是否可用
                val address = mActivityBinding.editTransferAddress.text.toString().trim()
                val amount = mActivityBinding.editTransferCount.text.toString().trim()
                if (address.isNotBlank() and amount.isNotBlank()) {
                    mActivityBinding.submitTransfer.setBackgroundResource(R.drawable.main_btn_hightlight)
                } else {
                    mActivityBinding.submitTransfer.setBackgroundResource(R.drawable.main_btn_ban)
                }
            }
        })
    }
}